<script lang="tsx">
/**
 * 帅特龙数据驾驶舱
 */
export default {
  name: "data-cockpit"
}
</script>

<script lang="tsx" setup>
import HeaderForm from "./components/header-form/index.vue"
import PassRateDaily from "./components/pass-rate-daily/index.vue"
import FinishRate from "./components/finish-rate/index.vue"
import PassStateDaily from "./components/pass-state-daily/index.vue"
import ProductionAchievementRate from "./components/production-achievement-rate/index.vue"
import BadReason from "./components/bad-reason/index.vue"
import ProductionTaskProgress from "./components/production-task-progress/index.vue"
import DeviceTotal from "./components/device-total/index.vue"
import DeviceState from "./components/device-state/index.vue"
import DeviceRate from "./components/device-rate/index.vue"
import WarningState from "./components/warning-state/index.vue"

import {onMounted, onUnmounted, ref} from "vue"
import {processRequest} from "@/frame/request/constructor.ts"
import {getDayDate, getMonthDate, getWeekDate, getYearDate} from "@/frame/utils/data-helper/calc-date.ts"
import {calcRate} from "@/frame/utils/data-helper/calc-rate.ts"
import {DateFilterEnum} from "@/pages/data-cockpit/index.ts"
import moment from "moment/moment"

/**
 * 时间类型
 */
const timer = ref()

/**
 * 最后刷新时间
 */
const refreshTime = ref()

/**
 * 挂载时运行
 */
onMounted(() => {
  getData()
  timer.value = setInterval(() => {
    getData()
  }, 60 * 1000)
})

/**
 * 取消挂载
 */
onUnmounted(() => {
  if (timer.value) {
    clearInterval(timer.value)
  }
})

/**
 * 获取数据
 */
const getData = () => {
  refreshTime.value = moment(new Date()).format("HH:mm:ss")
  //顶部

  //左侧
  //getProductionTaskProgressData()

  //中部
  //getDeviceTotalData()
  //getDeviceStateData()

  //右边
  //getDeviceRateData()
  //getWarningStateData()

  //顶部
  //getPassStateDailyData()
  //getFinishRateData()
  //getPassRateDailyData()

  //左侧
  //getProductionAchievementRateData()
  //getBadReasonData()
}

// region 当日综合合格率
const passRateData = ref({
  processNum: 0,
  passNum: 0,
  rate: 0
})
const getPassRateDailyData = async () => {
  const date = getDayDate()
  const result: any = await processRequest.get("/local/api/MES/GetOrderProgressPerDay", {
    startDate: date.before,
    endData: date.before
  })
  const result1: any = await processRequest.get("/local/api/MES/GetBadFactorsPerDay", {
    startDate: date.before,
    endData: date.now
  })
  const pass = result?.[0]?.comQty
  const process = pass + result1.reduce((memo: number, item: any) => {
    return memo + item.qty
  }, 0)
  passRateData.value = {
    processNum: process,
    passNum: pass,
    rate: calcRate(pass, process, 2)
  }
}
// endregion

// region 获取当日/当月完成率
const finishRateData = ref({
  planNumDaily: 0,
  actualNumDaily: 0,
  rateDaily: 0,
  planNumMonth: 0,
  actualNumMonth: 0,
  rateMonth: 0
})
const getFinishRateData = async () => {
  const date = getDayDate()
  const date1 = getMonthDate()
  const result: any = await processRequest.get("/local/api/MES/GetOrderProgressPerDay", {
    startDate: date.before,
    endData: date.before
  })
  const result1: any = await processRequest.get("/local/api/MES/GetOrderProgressPerMonth", {
    startDate: date1.before,
    endData: date1.now
  })
  const planNumDaily = result?.[0]?.planQty
  const actualNumDaily = result?.[0].comQty
  const planNumMonth = result1?.[0]?.planQty
  const actualNumMonth = result1?.[0].comQty
  finishRateData.value = {
    planNumDaily: planNumDaily,
    actualNumDaily: actualNumDaily,
    rateDaily: calcRate(actualNumDaily, planNumDaily, 2),
    planNumMonth: planNumMonth,
    actualNumMonth: actualNumMonth,
    rateMonth: calcRate(actualNumMonth, planNumMonth, 2)
  }
}
// endregion

// region 设备开工率
const passStateDailyData = ref({
  rateDaily: 0,
  rateWeek: 0
})
const getPassStateDailyData = async () => {
  const date = getDayDate()
  const result: any = await processRequest.get("/api/DevIotBoard/GetAllDevIotOperatingRateStatistics", {
    startTime: date.before,
    endTime: date.now
  })
  const date1 = getWeekDate()
  const result1: any = await processRequest.get("/api/DevIotBoard/GetAllDevIotOperatingRateStatistics", {
    startTime: date1.before,
    endTime: date1.now
  })
  passStateDailyData.value = {
    rateDaily: result?.number_UtilizationRate_Avg,
    rateWeek: result1?.number_UtilizationRate_Avg
  }
}
// endregion

// region 产量达成率
const productionAchievementRateDateType = ref(DateFilterEnum.周)
const productionAchievementRateData = ref([])
const getProductionAchievementRateData = async () => {
  if (productionAchievementRateDateType.value === DateFilterEnum.周) {
    const date = getWeekDate()
    const result: any = await processRequest.get("/local/api/MES/GetOrderProgressPerDay", {
      startDate: date.before,
      endData: date.now
    })
    productionAchievementRateData.value = result.map((item: any) => {
      return {
        day: item.orderDate?.split("-")?.[1] + "." + item.orderDate?.split("-")?.[2],
        plan: item.planQty,
        actual: item.comQty
      }
    })
  } else if (productionAchievementRateDateType.value === DateFilterEnum.月) {
    const date = getMonthDate()
    const result: any = await processRequest.get("/local/api/MES/GetOrderProgressPerDay", {
      startDate: date.before,
      endData: date.now
    })
    productionAchievementRateData.value = result.map((item: any) => {
      return {
        day: item.orderDate?.split("-")?.[1] + "." + item.orderDate?.split("-")?.[2],
        plan: item.planQty,
        actual: item.comQty
      }
    })
  } else {
    const date = getYearDate()
    const result: any = await processRequest.get("/local/api/MES/GetOrderProgressPerMonth", {
      startDate: date.before,
      endData: date.now
    })
    productionAchievementRateData.value = result.map((item: any) => {
      return {
        day: item.orderDate?.split("-")?.[1],
        plan: item.planQty,
        actual: item.comQty
      }
    })
  }
}
const productionAchievementRateChange = (value: any) => {
  productionAchievementRateDateType.value = value
  getProductionAchievementRateData()
}
// endregion

// region 不良原因分析
const badReasonDateType = ref(DateFilterEnum.周)
const badReasonData = ref([])
const getBadReasonData = async () => {
  if (badReasonDateType.value === DateFilterEnum.周) {
    const date = getWeekDate()
    const result: any = await processRequest.get("/local/api/MES/GetBadFactors", {
      startDate: date.before,
      endData: date.now
    })
    badReasonData.value = result.map((item: any) => {
      return {
        name: item.name,
        num: item.qty
      }
    })
  } else if (badReasonDateType.value === DateFilterEnum.月) {
    const date = getMonthDate()
    const result: any = await processRequest.get("/local/api/MES/GetBadFactors", {
      startDate: date.before,
      endData: date.now
    })
    badReasonData.value = result.map((item: any) => {
      return {
        name: item.name,
        num: item.qty
      }
    })
  } else {
    const date = getYearDate()
    const result: any = await processRequest.get("/local/api/MES/GetBadFactorsPerMonth", {
      startDate: date.before,
      endData: date.now
    })
    badReasonData.value = result.map((item: any) => {
      return {
        name: item.name,
        num: item.qty
      }
    })
  }
}
const badReasonChange = (value: any) => {
  badReasonDateType.value = value
  getBadReasonData()
}
const calcTotal = (data: any) => {
  const list = data.reduce((acc: any, item: any) => {
    const name = item.name
    acc[name] = (acc[name] || 0) + item.qty
    return acc
  }, {})
  return Object.entries(list).map(([name, totalQty]) => ({
    name,
    totalQty
  }))
}
// endregion

// region 获取生产任务进度
const productionTaskProgressData = ref([])
const getProductionTaskProgressData = async () => {
  const date = getDayDate()
  const result: any = await processRequest.get("/api/DevIotBoard/GetDevIotProductionStatusList", {
    // startTime: date.before,
    // endTime: date.now
  })
  productionTaskProgressData.value = result.map((item: any) => {
    return {
      code: item.orderNo,
      goodsCode: item.goodsCode,
      plan: item.num_Plan || 0,
      progress: item.number_Finish || 0
    }
  })
}
// endregion

// region 设备统计
const deviceTotalData = ref([
  {
    title: "故障",
    data: 0,
    src: "/img/data-cockpit/device-total/device-error.png"
  },
  {
    title: "闲置",
    data: 0,
    src: "/img/data-cockpit/device-total/device-idle.png"
  },
  {
    title: "运行",
    data: 0,
    src: "/img/data-cockpit/device-total/device-run.png"
  },
  {
    title: "校正",
    data: 0,
    src: "/img/data-cockpit/device-total/device-correct.png"
  },
  {
    title: "关机",
    data: 0,
    src: "/img/data-cockpit/device-total/device-close.png"
  }
])
const getDeviceTotalData = async () => {
  const result: any = await processRequest.get("/api/DevIotBoard/GetDevIotStatusCount")
  deviceTotalData.value[0].data = result.anomalyCount
  deviceTotalData.value[1].data = result.standbyCount
  deviceTotalData.value[2].data = result.runCount
  deviceTotalData.value[3].data = result.correctionCount
  deviceTotalData.value[4].data = result.closeCount
}
// endregion

// region 设备状态
const deviceStateData = ref([])
const getDeviceStateData = async () => {
  const date = getDayDate()
  const result: any = await processRequest.get("/api/DevIotBoard/GetDevIotUtilizationRateList", {
    // startTime: date.before,
    // endTime: date.now
  })
  deviceStateData.value = result.map((item: any) => {
    return {
      name: item.deviceName,
      rate: item.number_UtilizationRate,
      status: item.status
    }
  })
}
// endregion

// region 设备稼动率排行率
const deviceRateData = ref([])
const getDeviceRateData = async () => {
  const date = getDayDate()
  const result: any = await processRequest.get("/api/DevIotBoard/GetDevIotUtilizationRateList", {
    topCount: 4
    // startTime: date.before,
    // endTime: date.now
  })
  deviceRateData.value = result.map((item: any, index: number) => {
    const active = item.number_UtilizationRate < 5 ? 0 : item.number_UtilizationRate > 95 ? 18 : Number(((item.number_UtilizationRate) / 5 - 1).toFixed(0))
    return {
      index: `NO.0${index + 1}`,
      deviceName: item.deviceName,
      rate: item.number_UtilizationRate,
      active: active,
      normal: 18 - active
    }
  })
}
// endregion

// region 获取预警分析
const warningStateData = ref([])
const getWarningStateData = async () => {
  const date = getDayDate()
  const result: any = await processRequest.get("/api/DevIotBoard/GetDevIotNodeWarnList", {
    // startTime: date.before,
    // endTime: date.now
  })
  warningStateData.value = result.map((item: any) => {
    const hour = item.createDate?.split(" ")?.[1]?.split(":")[0]
    const minute = item.createDate?.split(" ")?.[1]?.split(":")[1]
    return {
      time: `${hour}:${minute}`,
      deviceCode: item.deviceCode,
      deviceName: item.deviceName,
      badReason: item.warn_Message
    }
  })
}
// endregion
</script>

<template>
  <div class="page-wrap">
    <div class="page-header">
      <HeaderForm :refreshTime="refreshTime"/>
    </div>
    <div class="page-summary">
      <PassRateDaily :passRateData="passRateData"/>
      <FinishRate :finishRateData="finishRateData"/>
      <PassStateDaily :passStateDailyData="passStateDailyData"/>
    </div>
    <div class="page-data">
      <div class="data-left">
        <ProductionAchievementRate :productionAchievementRateData="productionAchievementRateData"
                                   @change="productionAchievementRateChange"/>
        <BadReason :badReasonData="badReasonData" @change="badReasonChange"/>
        <ProductionTaskProgress :productionTaskProgressData="productionTaskProgressData"/>
      </div>
      <div class="data-middle">
        <DeviceTotal :deviceTotalData="deviceTotalData"/>
        <DeviceState :deviceStateData="deviceStateData"/>
      </div>
      <div class="data-right">
        <DeviceRate :deviceRateData="deviceRateData"/>
        <WarningState :warningStateData="warningStateData"/>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped src="./index.scss">

</style>